package com.lipuwater.agent.ble;

import android.os.Handler;

import com.blekit.BluetoothClient;
import com.blekit.connect.response.BleNotifyResponse;
import com.lipuwater.agent.ble.eventbus.DeviceWriteEvent;
import com.lipuwater.agent.ble.listener.NoticeListener;
import com.lipuwater.agent.ble.utils.ByteUtils;
import com.lipuwater.agent.ui.activity.MainActivity;
import com.ismartlib.utils.L;

import java.util.UUID;

import de.greenrobot.event.EventBus;

import static com.blekit.Code.REQUEST_SUCCESS;

/**
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃永无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by  Administrator  on 2016/11/28.
 * Email:924686754@qq.com
 * 监听设备回调通知
 */
public class DeviceNotice {
    private UUID NOTICE_SERVICE_UUID = UUID.fromString(BleConfig.NOTICE_SERVICE_UUID);
    private UUID NOTICE_NOTIFICATION_UUID = UUID.fromString(BleConfig.NOTICE_NOTIFICATION_UUID);
    private BluetoothClient mClient;
    private NoticeListener mNoticeListener;
    private boolean mWriteData = false;
    private Handler mWriteDataHandler = new Handler();//检测设备无响应

    public void Notify(String mac, NoticeListener noticeListener) {
        mClient = MainActivity.mBleClient;
        if (mClient == null) {
            return;
        }
        EventBus.getDefault().register(DeviceNotice.this);
        this.mNoticeListener = noticeListener;
        mClient.notify(mac, NOTICE_SERVICE_UUID, NOTICE_NOTIFICATION_UUID, new BleNotifyResponse() {
            @Override
            public void onNotify(UUID service, UUID character, byte[] value) {
                L.i("value:" + ByteUtils.toHexString(value));
                mWriteData = false;
                concat(value);
            }

            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {
                    //打开成功
                    L.i("打开服务成功");
                } else {
                    L.i("打开服务失败");
                }
            }
        });
    }

    /**
     * 成功写入指令通知
     */
    public void onEvent(DeviceWriteEvent event) {
        mWriteData = true;
        mWriteDataHandler.removeCallbacksAndMessages(null);
        mWriteDataHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mWriteDataHandler.removeCallbacksAndMessages(null);
                if (mWriteData) {
                    notice(bytes, receive, true);
                }
            }
        }, BleConfig.RESPONSE_TIME_OUT);
    }

    public void unNotify() {
        mNoticeListener = null;
    }

    public byte[] bytes = null;
    public int length = 0;   //数据长度
    private int receive;//消息序列号
    public int position = 0;
    public int packageHead = 3;
    public int FF = -1;
    public boolean complete = false;
    public Handler mHandler = new Handler();

    private void concat(byte[] value) {
        try {
            if (length != 0) {
                for (int i = 0; i < value.length; i++) {
                    bytes[position] = value[i];
                    if (value[i] == FF) {
                        i++;
                    }
                    position++;
                }
                if (position == length + packageHead) {
                    complete = true;
                    notice(bytes, receive, false);
                    length = 0;
                    receive = 0;
                    position = 0;
                    bytes = null;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.removeCallbacksAndMessages(null);
                        if (!complete) {
                            complete = false;
                            notice(bytes, receive, true);
                            position = 0;
                            receive = 0;
                            length = 0;
                            bytes = null;
                        }
                    }
                }, 500);
            } else {
                if (value[0] != FF || value[1] != FF) {
                    throw new Exception("丢包了");
                } else {
                    length = ByteUtils.byteTo10(value[2]);
                    receive = value[3];
                    bytes = new byte[(length + packageHead)];
                    position = 0;
                    for (int i = 0; i < value.length; i++) {
                        bytes[position] = value[i];
                        if (position > 1 && value[i] == FF) {
                            i++;
                        }
                        position++;
                    }
                    if (position == length + packageHead) {
                        complete = true;
                        notice(bytes, receive, false);
                        length = 0;
                        receive = 0;
                        position = 0;
                        bytes = null;
                    }
                }
            }
        } catch (Exception e) {
            //丢包了
            complete = false;
            mHandler.removeCallbacksAndMessages(null);
            notice(bytes, receive, true);
            position = 0;
            length = 0;
            receive = 0;
            bytes = null;
            L.i("xxxxxx", "丢包了");
        }
    }

    private void notice(byte[] value, int receiveMsg, boolean losePackage) {
        if (mNoticeListener != null) {
            mNoticeListener.BleNotice(value, receiveMsg, losePackage);
        }
    }
}
